package src.zoo 
{
	import flash.utils.setInterval;
	import flash.utils.clearInterval;
	
	public class VirtualPet 
	{
		private static var maxNameLength: int = 20;
		private static var maxCalories:int = 2000;
		private static var caloriesPerSecond: int = 100;
		
		private var petName: String;
		private var currentCalories: int = maxCalories / 2;
		private var creationTime: Date;
		private var digestIntervalID: uint;
		
		public function VirtualPet(name: String) 
		{
			creationTime = new Date();
			setName(name);
			digestIntervalID = setInterval(digest, 1000);
		}
		
		public function eat (foodItem: Food): void
		{
			if (currentCalories == 0)
			{
				trace(petName + " умер. Вы больше не можете его кормить.");
				return;
			}
			
			currentCalories += foodItem.getCalories;
			
			if (currentCalories > maxCalories)
			{
				currentCalories = maxCalories;
			}
			
			trace(petName + " поел.");
		}
		
		public function getAge(): int
		{
			var currentTime: Date = new Date;
			var age: int = currentTime.time - creationTime.time;
			
			return age;
		}
		
		public function setName(name: String): void
		{
			if (name.length > maxNameLength)
			{
				name = name.substr(0, maxNameLength);
			}
			else if (name == "")
			{
				return;
			}
			
			petName = name;
		}
		
		private function digest(): void
		{
			if ((currentCalories - caloriesPerSecond) <= 0)
			{
				clearInterval(digestIntervalID);
				currentCalories = 0;
				trace(petName + " умер.");
			}
			else
			{
				currentCalories -= caloriesPerSecond;
			}
		}
		
	}

}